package com.example.treehole.ui.page.square

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.treehole.LocalSquareViewModel
import com.example.treehole.LocalUserViewModel
import com.example.treehole.ui.component.PostCard
import com.example.treehole.ui.component.RefreshBox
import com.example.treehole.ui.component.SearchBox
import com.example.treehole.ui.model.PostInfo
import com.example.treehole.ui.model.PostType
import com.example.treehole.ui.model.TagSection
import kotlinx.coroutines.launch

@Composable
fun SquareScreen() {
    val userViewModel = LocalUserViewModel.current
    val userId by userViewModel.userId.collectAsState()
    val jwlToken by userViewModel.jwlToken.collectAsState()
    val scope = rememberCoroutineScope()

    val squareViewModel = LocalSquareViewModel.current
    val selectedTag by squareViewModel.selectedTag.collectAsState()

    val squarePostListViewModel = SquarePostListViewModel()
    val postList by squarePostListViewModel.squarePostList.collectAsState()
    val page by squarePostListViewModel.squarePage.collectAsState()

    val searchMode = remember { mutableStateOf(false) }
    val searchText = remember { mutableStateOf("") }

    // 下拉刷新
    val isRefreshing = remember { mutableStateOf(false) }
    // 底部加载
    val isLoading = remember { mutableStateOf(false) }
    val listState = LazyListState()

    LaunchedEffect(listState) {
        if (postList.isEmpty() && !searchMode.value ) {
            userId?.let {
                isRefreshing.value = true
                squarePostListViewModel.refreshTagPost(jwlToken, it, selectedTag)
                isRefreshing.value = false
            }
        } else if(!searchMode.value) {
            snapshotFlow {
                listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index == postList.size - 1
            }
                .collect { isAtBottom ->
                    if (!searchMode.value &&
                        isAtBottom &&
                        !isRefreshing.value &&
                        !isLoading.value &&
                        page != -2
                    ) {
                        userId?.let {
                            isLoading.value = true
                            squarePostListViewModel.getMoreTagPost(jwlToken, it, selectedTag)
                            isLoading.value = false
                        }
                    }
                }
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        if (selectedTag == PostType.NO_TYPE) {
            LazyVerticalGrid(
                columns = GridCells.Fixed(2),
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(8.dp)
            ) {
                items(squareViewModel.tags.filter { it.type != PostType.NO_TYPE }) { item: TagSection ->
                    SectionCard(item)
                }
            }
        } else {
            BackHandler {
                if (searchMode.value) {
                    searchMode.value = false
                    searchText.value = ""
                    scope.launch {
                        userId?.let {
                            squarePostListViewModel.refreshTagPost(jwlToken,
                                it,selectedTag)
                        }
                    }
                } else {
                    squareViewModel.updateTag(PostType.NO_TYPE)
                    squarePostListViewModel.updateSquarePostList(emptyList())
                }
            }
            Column(modifier = Modifier.fillMaxSize()) {
                SearchBox(
                    searchText = searchText,
                    searchMode = searchMode,
                    onSearch = {
                        scope.launch {
                            userId?.let {
                                squarePostListViewModel.searchTagPost(
                                    jwlToken,
                                    searchText.value,
                                    it,
                                    selectedTag
                                )
                            }
                        }
                    }
                )
                RefreshBox(
                    isRefreshing = isRefreshing,
                    onRefresh = {
                        userId?.let {
                            squarePostListViewModel.refreshTagPost(jwlToken, it, selectedTag)
                        }
                    }
                ) {
                    if (postList.isNotEmpty()) {
                        LazyColumn(state = listState) {
                            items(postList) { item: PostInfo -> PostCard(post = item) }
                        }
                    } else {
                        Box(modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState()),
                            contentAlignment = Alignment.Center
                        ){
                            Text(
                                text = if(!searchMode.value) "好像出了一点点小错误..." else "没有搜索到相关贴子",
                                fontSize = 24.sp,
                                color = Color.White)
                        }
                    }
                }
            }
        }
    }
}
